package com.fsd.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.springframework.stereotype.Repository;

import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_parameterlist;
import com.fsd.admin.model.Sys_SystemParameters;
import com.fsd.admin.service.B_parameterlistService;
import com.fsd.admin.dao.B_parameterlistDao;
import com.google.gson.Gson;

@Repository("b_parameterlistServiceImpl")
public class B_parameterlistServiceImpl extends MainServiceImpl<B_parameterlist, String> implements B_parameterlistService{
    
    private static final Logger log = Logger.getLogger(B_parameterlistServiceImpl.class);
    private String depict = "参数列表";
    
    @Resource(name = "b_parameterlistDaoImpl")
	public void setBaseDao(B_parameterlistDao b_parameterlistDao) {
		super.setBaseDao(b_parameterlistDao);
	}
	
	@Resource(name = "b_parameterlistDaoImpl")
	private B_parameterlistDao objectDao;
	
	/**
     * 状态启用
     */
	public static final String csqy1 = "csqy";
	public static final String csqy2 = "启用";
	/**
     * 状态停用
     */
	public static final String csty1 = "csty";
	public static final String csty2 = "停用";
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("parametertypeid"));
		c.addOrder(Order.asc("sort"));
		c.addOrder(Order.asc("name"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.or(
						Restrictions.eq("parametertypeid", objectMap.get("fid")),
						Restrictions.eq("companyid", objectMap.get("fid"))
						));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(B_parameterlist obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			B_parameterlist obj_old = objectDao.get(obj.getId());
			obj_old.setParametertypeid(obj.getParametertypeid());
			obj_old.setParametertypename(obj.getParametertypename());
			obj_old.setName(obj.getName());
			obj_old.setSymbol(obj.getSymbol());
			obj_old.setTitle(obj.getTitle());
			obj_old.setBelongsid(obj.getBelongsid());
			obj_old.setUrlpath(obj.getUrlpath());
			obj_old.setImagepath(obj.getImagepath());
			obj_old.setParameter1(obj.getParameter1());
			obj_old.setParameter2(obj.getParameter2());
			obj_old.setParameter3(obj.getParameter3());
			obj_old.setSort(obj.getSort());
			obj_old.setRemark(obj.getRemark());
			obj_old.setStatus(csty1);
			obj_old.setStatusname(csty2);
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			objectDao.update(obj_old);
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setStatus(csty1);
			obj.setStatusname(csty2);
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(obj);
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, B_parameterlistServiceImpl.class);
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		objectDao.executeHql("update B_parameterlist t set t.deleted = '1' where t.id in (" + ids + ")");
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public B_parameterlist getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		B_parameterlist obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 修改对象状态
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateEnabledObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		if (isEnabled)
			objectDao.executeHql("update B_parameterlist t set t.status = 'csqy', t.statusname = '启用' where t.id in (" + ids + ")");
		else
			objectDao.executeHql("update B_parameterlist t set t.status = 'csty', t.statusname = '停用' where t.id in (" + ids + ")");
	}
	
	/**
	 * 加载所有数据
	 * @return
	 * @throws Exception
	 */
	public List<B_parameterlist> getObjectList(A_Employee employee) throws Exception{
		return objectDao.queryByHql("from B_parameterlist a where a.companyid = '"+ employee.getCompanyid() +"' and a.deleted = '0'");
	}
	
	/**
	 * 生成Excel文件
	 * @param list
	 * @param url
	 * @param sheetName
	 * @throws Exception
	 */
	public void createExcel(List<B_parameterlist> parameterList, String url) throws Exception{
		WritableWorkbook book = Workbook.createWorkbook(new File(url)); //创建可写入的 Excel 工作薄
		WritableCellFormat format = new WritableCellFormat();
		WritableFont font = new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD); //字形
		format.setFont(font);
		format.setAlignment(Alignment.CENTRE);
		format.setVerticalAlignment(VerticalAlignment.CENTRE);
		format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);  //边框
		
		WritableCellFormat cellformat = new WritableCellFormat();
		cellformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		cellformat.setWrap(true);  //设置单元格自适应列宽
		
		WritableCellFormat headerformat = new WritableCellFormat();
		WritableFont hFont = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD); //字形加粗
		headerformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		headerformat.setFont(hFont);
		
		WritableSheet sheet = book.createSheet("参数列表", 0);

		sheet.mergeCells(0,0,21,0); //a:最左上的列，b最左上的行，c最右下的列，d最右下的行 （合并单元格）
		sheet.getSettings().setDefaultColumnWidth(20);
		sheet.setColumnView(0,10);  //单独设置列宽 （0代表第几列，10代表宽度）
		Label label = new Label(0, 0, "参数列表", format);
		sheet.addCell(label);
		for (int i = 0; i < 22; i++) {
			Label label_tem = null;
			switch (i) {
			case 0:
				label_tem = new Label(i, 1, "",headerformat);
				break;
			case 1:
				label_tem = new Label(i, 1, "编号",headerformat);
				break;
			case 2:
				label_tem = new Label(i, 1, "所属单位",headerformat);
				break;
			case 3:
				label_tem = new Label(i, 1, "所属参数ID",headerformat);
				break;
			case 4:
				label_tem = new Label(i, 1, "所属参数名称",headerformat);
				break;
			case 5:
				label_tem = new Label(i, 1, "名称",headerformat);
				break;
			case 6:
				label_tem = new Label(i, 1, "助记符",headerformat);
				break;
			case 7:
				label_tem = new Label(i, 1, "显示标题",headerformat);
				break;
			case 8:
				label_tem = new Label(i, 1, "对应数据ID",headerformat);
				break;
			case 9:
				label_tem = new Label(i, 1, "链接地址",headerformat);
				break;
			case 10:
				label_tem = new Label(i, 1, "图片地址",headerformat);
				break;
			case 11:
				label_tem = new Label(i, 1, "扩展参数1",headerformat);
				break;
			case 12:
				label_tem = new Label(i, 1, "扩展参数2",headerformat);
				break;
			case 13:
				label_tem = new Label(i, 1, "扩展参数3",headerformat);
				break;
			case 14:
				label_tem = new Label(i, 1, "序号",headerformat);
				break;
			case 15:
				label_tem = new Label(i, 1, "状态",headerformat);
				break;
			case 16:
				label_tem = new Label(i, 1, "状态名称",headerformat);
				break;
			case 17:
				label_tem = new Label(i, 1, "备注",headerformat);
				break;
			case 18:
				label_tem = new Label(i, 1, "新增时间",headerformat);
				break;
			case 19:
				label_tem = new Label(i, 1, "新增人ID",headerformat);
				break;
			case 20:
				label_tem = new Label(i, 1, "新增人名称",headerformat);
				break;
			case 21:
				label_tem = new Label(i, 1, "删除标志",headerformat);
				break;
			default:
				break;
			}
			sheet.addCell(label_tem);
		}
		for (int j = 0; j < parameterList.size(); j++){
			sheet.addCell(new Label(0,j+2, j+1+"",cellformat));
			sheet.addCell(new Label(1,j+2, parameterList.get(j).getId(),cellformat));
			sheet.addCell(new Label(2,j+2, parameterList.get(j).getCompanyid(),cellformat));
			sheet.addCell(new Label(3,j+2, parameterList.get(j).getParametertypeid(),cellformat));
			sheet.addCell(new Label(4,j+2, parameterList.get(j).getParametertypename(),cellformat));
			sheet.addCell(new Label(5,j+2, parameterList.get(j).getName(),cellformat));
			sheet.addCell(new Label(6,j+2, parameterList.get(j).getSymbol(),cellformat));
			sheet.addCell(new Label(7,j+2, parameterList.get(j).getTitle(),cellformat));
			sheet.addCell(new Label(8,j+2, parameterList.get(j).getBelongsid(),cellformat));
			sheet.addCell(new Label(9,j+2, parameterList.get(j).getUrlpath(),cellformat));
			sheet.addCell(new Label(10,j+2, parameterList.get(j).getImagepath(),cellformat));
			sheet.addCell(new Label(11,j+2, parameterList.get(j).getParameter1(),cellformat));
			sheet.addCell(new Label(12,j+2, parameterList.get(j).getParameter2(),cellformat));
			sheet.addCell(new Label(13,j+2, parameterList.get(j).getParameter3(),cellformat));
			sheet.addCell(new Label(14,j+2, String.valueOf(parameterList.get(j).getSort()),cellformat));
			sheet.addCell(new Label(15,j+2, parameterList.get(j).getStatus(),cellformat));
			sheet.addCell(new Label(16,j+2, parameterList.get(j).getStatusname(),cellformat));
			sheet.addCell(new Label(17,j+2, parameterList.get(j).getRemark(),cellformat));
			sheet.addCell(new Label(18,j+2, parameterList.get(j).getAdddate(),cellformat));
			sheet.addCell(new Label(19,j+2, parameterList.get(j).getAddemployeeid(),cellformat));
			sheet.addCell(new Label(20,j+2, parameterList.get(j).getAddemployeename(),cellformat));
			sheet.addCell(new Label(21,j+2, parameterList.get(j).getDeleted(),cellformat));
		}
		book.write();
		book.close();
	}
	
	/**
	 * Excel导出
	 */
	public Map<String, String> download(A_Employee employee, String rootPath, String httpRootPath) throws Exception {
		List<B_parameterlist> parameterList = this.getObjectList(employee);
		String path = "uploadfiles/temp/"+UUID.randomUUID().toString().trim().replaceAll("-", "")+".xls";
		String url = rootPath+path;
		String httpUrl = httpRootPath+path;
		this.createExcel(parameterList, url);
		Map<String, String> map = new HashMap<String, String>();
		map.put("httpUrl", httpUrl);
		return map;
	}
	
	/**
	 * 顺序排序
	 * @param parameters
	 */
	public void updateSortObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		List<String> idList = (List<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		B_parameterlist obj = objectDao.get(objectMap.get("id").toString());
		if (obj == null)
			throw new BusinessException(depict + "获取定位对象为空!");
		List<B_parameterlist> objList = objectDao.queryByHql("from B_parameterlist t where " +
				"t.parametertypeid = '" + obj.getParametertypeid() + "' and t.deleted = '0' " +
				"and t.id not in (" + ids + ") " +
				"and t.sort >= " + obj.getSort() + " order by t.sort asc");
		long sort = obj.getSort();
		for (String id : idList) {
			objectDao.executeHql("update B_parameterlist t set t.sort = " + sort + " where t.id = '" + id + "'");
			sort++;
		}
		for (B_parameterlist obj1 : objList) {
			objectDao.executeHql("update B_parameterlist t set t.sort = " + sort + " where t.id = '" + obj1.getId() + "'");
			sort++;
		}
	}
}
